Salvaging hardware transactions

ABSTRACT

A transactional memory system salvages a partially executed hardware transaction. A processor of the transactional memory system saves state information in a first code region of a first hardware transaction. The processor executes an about-to-fail handler, the about-to-fail handler using the saved state information to determine whether the first hardware transaction is to be salvaged or to be aborted. The processor executing the about-to-fail handler, based on the transaction being to be salvaged, uses the saved state information to determine what portion of the first hardware transaction to salvage.

BACKGROUND

This disclosure relates generally to transactional execution, and morespecifically to salvaging partially executed hardware transactions.

The number of central processing unit (CPU) cores on a chip and thenumber of CPU cores connected to a shared memory continues to growsignificantly to support growing workload capacity demand. Theincreasing number of CPUs cooperating to process the same workloads putsa significant burden on software scalability; for example, shared queuesor data-structures protected by traditional semaphores become hot spotsand lead to sub-linear n-way scaling curves. Traditionally this has beencountered by implementing finer-grained locking in software, and withlower latency/higher bandwidth interconnects in hardware. Implementingfine-grained locking to improve software scalability can be verycomplicated and error-prone, and at today's CPU frequencies, thelatencies of hardware interconnects are limited by the physicaldimension of the chips and systems, and by the speed of light.

Implementations of hardware Transactional Memory (HTM, or in thisdiscussion, simply TM) have been introduced, wherein a group ofinstructions, called a transaction, operate in an atomic manner on adata structure in memory, as viewed by other central processing units(CPUs) and the I/O subsystem (atomic operation is also known as “blockcurrent” or “serialized” in other literature). The transaction executesoptimistically without obtaining a lock, but may need to abort and retrythe transaction execution if an operation, of the executing transaction,on a memory location conflicts with another operation on the same memorylocation. Previously, software transactional memory implementations havebeen proposed to support software Transactional Memory (TM). However,hardware TM can provide improved performance aspects and ease of useover software TM.

U.S. Patent Publication No. 2007/0028056 titled “Direct-Update SoftwareTransactional Memory” filed Jul. 29, 2005, incorporated herein byreference in its entirety, teaches a transactional memory programminginterface that allows a thread to directly and safely access one or moreshared memory locations within a transaction while maintaining controlstructures to manage memory accesses to those same locations by one ormore other concurrent threads. Each memory location accessed by thethread is associated with an enlistment record, and each threadmaintains a transaction log of its memory accesses. Within atransaction, a read operation is performed directly on the memorylocation and a write operation is attempted directly on the memorylocation, as opposed to some intermediate buffer. The thread can detectinconsistencies between the enlistment record of a memory location andthe thread's transaction log to determine whether the memory accesseswithin the transaction are not reliable and the transaction should bere-tried.

U.S. Patent Publication No. 2011/0119452 titled “Hybrid TransactionalMemory System (Hybrid™) and Method” filed Nov. 6, 2009, incorporatedherein by reference in its entirety, teaches a computer processingsystem having memory and processing facilities for processing data witha computer program is a Hybrid Transactional Memory multiprocessorsystem with modules 1 . . . n coupled to a system physical memory array,I/O devices via a high speed interconnection element. A CPU isintegrated as in a multi-chip module with microprocessors which containor are coupled in the CPU module to an assist thread facility, as wellas a memory controller, cache controllers, cache memory, and othercomponents which form part of the CPU which connects to the high speedinterconnect which functions under the architecture and operating systemto interconnect elements of the computer system with physical memory,various I/O devices and the other CPUs of the system. The current hybridtransactional memory elements support for a transaction memory systemthat has a simple/cost effective hardware design that can deal withlimited hardware resources, yet one which has a transactional facilitycontrol logic providing for a backup assist thread that can still allowtransactions to reference existing libraries and allows programmers toinclude calls to existing software libraries inside of theirtransaction, and which will not make a user code use a second lock basedsolution.

SUMMARY

Embodiments of the present disclosure provide a method, computer programproduct, and computer system for a transactional memory system thatsalvages a partially executed hardware transaction. A processor of thetransactional memory system saves state information in a first coderegion of a first hardware transaction. The processor executes anabout-to-fail handler, the about-to-fail handler using the saved stateinformation to determine whether the first hardware transaction is to besalvaged or to be aborted. The processor executing the about-to-failhandler, based on the transaction being to be salvaged, uses the savedstate information to determine what portion of the first hardwaretransaction to salvage.

BRIEF DESCRIPTION OF THE SEVERAL VIEWS OF THE DRAWINGS

One or more aspects of the present disclosed embodiments areparticularly pointed out and distinctly claimed as examples in theclaims at the conclusion of the specification. The foregoing and otherobjects, features, and advantages of the disclosed embodiments areapparent from the following detailed description taken in conjunctionwith the accompanying drawings in which:

FIGS. 1 and 2 depict block diagrams of an example multi-coreTransactional Memory environment, in accordance with embodiments of thepresent disclosure;

FIG. 3 depicts a block diagram including example components of anexample CPU, in accordance with embodiments of the present disclosure;

FIG. 4 depicts a flow diagram illustrating an embodiment for salvaging apartially executed hardware transaction upon detection of a fault, inaccordance with embodiments of the present disclosure;

FIG. 5 illustrates exemplary program code for implementing a softwarecomponent of the embodiment of FIG. 4, in accordance with embodiments ofthe present disclosure;

FIG. 6 depicts a flow diagram illustrating an embodiment of the presentinvention.

FIG. 7 depicts a flow diagram illustrating an embodiment of the presentinvention.

FIG. 8 depicts a flow diagram illustrating an embodiment of the presentinvention.

FIG. 9 depicts a flow diagram illustrating an embodiment of the presentinvention.

FIG. 10 depicts a functional block diagram of a computer system, inaccordance with embodiments of the present disclosure.

DETAILED DESCRIPTION

Historically, a computer system or processor had only a single processor(aka processing unit or central processing unit). The processor includedan instruction processing unit (IPU), a branch unit, a memory controlunit and the like. Such processors were capable of executing a singlethread of a program at a time. Operating systems were developed thatcould time-share a processor by dispatching a program to be executed onthe processor for a period of time, and then dispatching another programto be executed on the processor for another period of time. Astechnology evolved, memory subsystem caches were often added to theprocessor as well as complex dynamic address translation includingtranslation lookaside buffers (TLBs). The IPU itself was often referredto as a processor. As technology continued to evolve, an entireprocessor, could be packaged in a single semiconductor chip or die, sucha processor was referred to as a microprocessor. Then processors weredeveloped that incorporated multiple IPUs, such processors were oftenreferred to as multi-processors. Each such processor of amulti-processor computer system (processor) may include individual orshared caches, memory interfaces, system bus, address translationmechanism and the like. Virtual machine and instruction set architecture(ISA) emulators added a layer of software to a processor, that providedthe virtual machine with multiple “virtual processors” (aka processors)by time-slice usage of a single IPU in a single hardware processor. Astechnology further evolved, multi-threaded processors were developed,enabling a single hardware processor having a single multi-thread IPU toprovide a capability of simultaneously executing threads of differentprograms, thus each thread of a multi-threaded processor appeared to theoperating system as a processor. As technology further evolved, it waspossible to put multiple processors (each having an IPU) on a singlesemiconductor chip or die. These processors were referred to processorcores or just cores. Thus the terms such as processor, centralprocessing unit, processing unit, microprocessor, core, processor core,processor thread, and thread, for example, are often usedinterchangeably. Aspects of embodiments herein may be practiced by anyor all processors including those shown supra, without departing fromthe teachings herein. Wherein the term “thread” or “processor thread” isused herein, it is expected that particular advantage of the embodimentmay be had in a processor thread implementation.

Transaction Execution in Intel® Based Embodiments

In “Intel® Architecture Instruction Set Extensions ProgrammingReference” 319433-012A, February 2012, incorporated herein by referencein its entirety, Chapter 8 teaches, in part, that multi-threadedapplications may take advantage of increasing numbers of CPU cores toachieve higher performance. However, the writing of multi-threadedapplications requires programmers to understand and take into accountdata sharing among the multiple threads. Access to shared data typicallyrequires synchronization mechanisms. These synchronization mechanismsare used to ensure that multiple threads update shared data byserializing operations that are applied to the shared data, oftenthrough the use of a critical section that is protected by a lock. Sinceserialization limits concurrency, programmers try to limit the overheaddue to synchronization.

Intel® Transactional Synchronization Extensions (Intel® TSX) allow aprocessor to dynamically determine whether threads need to be serializedthrough lock-protected critical sections, and to perform thatserialization only when required. This allows the processor to exposeand exploit concurrency that is hidden in an application because ofdynamically unnecessary synchronization.

With Intel TSX, programmer-specified code regions (also referred to as“transactional regions” or just “transactions”) are executedtransactionally. If the transactional execution completes successfully,then all memory operations performed within the transactional regionwill appear to have occurred instantaneously when viewed from otherprocessors. A processor makes the memory operations of the executedtransaction, performed within the transactional region, visible to otherprocessors only when a successful commit occurs, i.e., when thetransaction successfully completes execution. This process is oftenreferred to as an atomic commit.

Intel TSX provides two software interfaces to specify regions of codefor transactional execution. Hardware Lock Elision (HLE) is a legacycompatible instruction set extension (comprising the XACQUIRE andXRELEASE prefixes) to specify transactional regions. RestrictedTransactional Memory (RTM) is a new instruction set interface(comprising the XBEGIN, XEND, and XABORT instructions) for programmersto define transactional regions in a more flexible manner than thatpossible with HLE. HLE is for programmers who prefer the backwardcompatibility of the conventional mutual exclusion programming model andwould like to run HLE-enabled software on legacy hardware but would alsolike to take advantage of the new lock elision capabilities on hardwarewith HLE support. RTM is for programmers who prefer a flexible interfaceto the transactional execution hardware. In addition, Intel TSX alsoprovides an XTEST instruction. This instruction allows software to querywhether the logical processor is transactionally executing in atransactional region identified by either HLE or RTM.

Since a successful transactional execution ensures an atomic commit, theprocessor executes the code region optimistically without explicitsynchronization. If synchronization was unnecessary for that specificexecution, execution can commit without any cross-thread serialization.If the processor cannot commit atomically, then the optimistic executionfails. When this happens, the processor will roll back the execution, aprocess referred to as a transactional abort. On a transactional abort,the processor will discard all updates performed in the memory regionused by the transaction, restore architectural state to appear as if theoptimistic execution never occurred, and resume executionnon-transactionally.

A processor can perform a transactional abort for numerous reasons. Aprimary reason to abort a transaction is due to conflicting memoryaccesses between the transactionally executing logical processor andanother logical processor. Such conflicting memory accesses may preventa successful transactional execution. Memory addresses read from withina transactional region constitute the read-set of the transactionalregion and addresses written to within the transactional regionconstitute the write-set of the transactional region. Intel TSXmaintains the read- and write-sets at the granularity of a cache line. Aconflicting memory access occurs if another logical processor eitherreads a location that is part of the transactional region's write-set orwrites a location that is a part of either the read- or write-set of thetransactional region. A conflicting access typically means thatserialization is required for this code region. Since Intel TSX detectsdata conflicts at the granularity of a cache line, unrelated datalocations placed in the same cache line will be detected as conflictsthat result in transactional aborts. Transactional aborts may also occurdue to limited transactional resources. For example, the amount of dataaccessed in the region may exceed an implementation-specific capacity.Additionally, some instructions and system events may causetransactional aborts. Frequent transactional aborts result in wastedcycles and increased inefficiency.

Hardware Lock Elision

Hardware Lock Elision (HLE) provides a legacy compatible instruction setinterface for programmers to use transactional execution. HLE providestwo new instruction prefix hints: XACQUIRE and XRELEASE.

With HLE, a programmer adds the XACQUIRE prefix to the front of theinstruction that is used to acquire the lock that is protecting thecritical section. The processor treats the prefix as a hint to elide thewrite associated with the lock acquire operation. Even though the lockacquire has an associated write operation to the lock, the processordoes not add the address of the lock to the transactional region'swrite-set nor does it issue any write requests to the lock. Instead, theaddress of the lock is added to the read-set. The logical processorenters transactional execution. If the lock was available before theXACQUIRE prefixed instruction, then all other processors will continueto see the lock as available afterwards. Since the transactionallyexecuting logical processor neither added the address of the lock to itswrite-set nor performed externally visible write operations to the lock,other logical processors can read the lock without causing a dataconflict. This allows other logical processors to also enter andconcurrently execute the critical section protected by the lock. Theprocessor automatically detects any data conflicts that occur during thetransactional execution and will perform a transactional abort ifnecessary.

Even though the eliding processor did not perform any external writeoperations to the lock, the hardware ensures program order of operationson the lock. If the eliding processor itself reads the value of the lockin the critical section, it will appear as if the processor had acquiredthe lock, i.e. the read will return the non-elided value. This behaviorallows an HLE execution to be functionally equivalent to an executionwithout the HLE prefixes.

An XRELEASE prefix can be added in front of an instruction that is usedto release the lock protecting a critical section. Releasing the lockinvolves a write to the lock. If the instruction is to restore the valueof the lock to the value the lock had prior to the XACQUIRE prefixedlock acquire operation on the same lock, then the processor elides theexternal write request associated with the release of the lock and doesnot add the address of the lock to the write-set. The processor thenattempts to commit the transactional execution.

With HLE, if multiple threads execute critical sections protected by thesame lock but they do not perform any conflicting operations on eachother's data, then the threads can execute concurrently and withoutserialization. Even though the software uses lock acquisition operationson a common lock, the hardware recognizes this, elides the lock, andexecutes the critical sections on the two threads without requiring anycommunication through the lock—if such communication was dynamicallyunnecessary.

If the processor is unable to execute the region transactionally, thenthe processor will execute the region non-transactionally and withoutelision. HLE enabled software has the same forward progress guaranteesas the underlying non-HLE lock-based execution. For successful HLEexecution, the lock and the critical section code must follow certainguidelines. These guidelines only affect performance; and failure tofollow these guidelines will not result in a functional failure.Hardware without HLE support will ignore the XACQUIRE and XRELEASEprefix hints and will not perform any elision since these prefixescorrespond to the REPNE/REPE IA-32 prefixes which are ignored on theinstructions where XACQUIRE and XRELEASE are valid. Importantly, HLE iscompatible with the existing lock-based programming model. Improper useof hints will not cause functional bugs though it may expose latent bugsalready in the code.

Restricted Transactional Memory (RTM)

Restricted Transactional Memory (RTM) provides a flexible softwareinterface for transactional execution. RTM provides three newinstructions—XBEGIN, XEND, and XABORT—for programmers to start, commit,and abort a transactional execution.

The programmer uses the XBEGIN instruction to specify the start of atransactional code region and the XEND instruction to specify the end ofthe transactional code region. If the RTM region could not besuccessfully executed transactionally, then the XBEGIN instruction takesan operand that provides a relative offset to the fallback instructionaddress.

A processor may abort RTM transactional execution for many reasons. Inmany instances, the hardware automatically detects transactional abortconditions and restarts execution from the fallback instruction addresswith the architectural state corresponding to that present at the startof the XBEGIN instruction and the EAX register updated to describe theabort status.

The XABORT instruction allows programmers to abort the execution of anRTM region explicitly. The XABORT instruction takes an 8-bit immediateargument that is loaded into the EAX register and will thus be availableto software following an RTM abort. RTM instructions do not have anydata memory location associated with them. While the hardware providesno guarantees as to whether an RTM region will ever successfully committransactionally, most transactions that follow the recommendedguidelines are expected to successfully commit transactionally. However,programmers must always provide an alternative code sequence in thefallback path to guarantee forward progress. This may be as simple asacquiring a lock and executing the specified code regionnon-transactionally. Further, a transaction that always aborts on agiven implementation may complete transactionally on a futureimplementation. Therefore, programmers must ensure the code paths forthe transactional region and the alternative code sequence arefunctionally tested.

Detection of HLE Support

A processor supports HLE execution if CPUID.07H.EBX.HLE [bit 4]=1.However, an application can use the HLE prefixes (XACQUIRE and XRELEASE)without checking whether the processor supports HLE. Processors withoutHLE support ignore these prefixes and will execute the code withoutentering transactional execution.

Detection of RTM Support

A processor supports RTM execution if CPUID.07H.EBX.RTM [bit 11]=1. Anapplication must check if the processor supports RTM before it uses theRTM instructions (XBEGIN, XEND, XABORT). These instructions willgenerate a #UD exception when used on a processor that does not supportRTM.

Detection of XTEST Instruction

A processor supports the XTEST instruction if it supports either HLE orRTM. An application must check either of these feature flags beforeusing the XTEST instruction. This instruction will generate a #UDexception when used on a processor that does not support either HLE orRTM.

Querying Transactional Execution Status

The XTEST instruction can be used to determine the transactional statusof a transactional region specified by HLE or RTM. Note, while the HLEprefixes are ignored on processors that do not support HLE, the XTESTinstruction will generate a #UD exception when used on processors thatdo not support either HLE or RTM.

Requirements for HLE Locks

For HLE execution to successfully commit transactionally, the lock mustsatisfy certain properties and access to the lock must follow certainguidelines.

An XRELEASE prefixed instruction must restore the value of the elidedlock to the value it had before the lock acquisition. This allowshardware to safely elide locks by not adding them to the write-set. Thedata size and data address of the lock release (XRELEASE prefixed)instruction must match that of the lock acquire (XACQUIRE prefixed) andthe lock must not cross a cache line boundary.

Software should not write to the elided lock inside a transactional HLEregion with any instruction other than an XRELEASE prefixed instruction,otherwise such a write may cause a transactional abort. In addition,recursive locks (where a thread acquires the same lock multiple timeswithout first releasing the lock) may also cause a transactional abort.Note that software can observe the result of the elided lock acquireinside the critical section. Such a read operation will return the valueof the write to the lock.

The processor automatically detects violations to these guidelines, andsafely transitions to a non-transactional execution without elision.Since Intel TSX detects conflicts at the granularity of a cache line,writes to data collocated on the same cache line as the elided lock maybe detected as data conflicts by other logical processors eliding thesame lock.

Transactional Nesting

Both HLE and RTM support nested transactional regions. However, atransactional abort restores state to the operation that startedtransactional execution: either the outermost XACQUIRE prefixed HLEeligible instruction or the outermost XBEGIN instruction. The processortreats all nested transactions as one transaction.

HLE Nesting and Elision

Programmers can nest HLE regions up to an implementation specific depthof MAX_HLE_NEST_COUNT. Each logical processor tracks the nesting countinternally but this count is not available to software. An XACQUIREprefixed HLE-eligible instruction increments the nesting count, and anXRELEASE prefixed HLE-eligible instruction decrements it. The logicalprocessor enters transactional execution when the nesting count goesfrom zero to one. The logical processor attempts to commit only when thenesting count becomes zero. A transactional abort may occur if thenesting count exceeds MAX_HLE_NEST_COUNT.

In addition to supporting nested HLE regions, the processor can alsoelide multiple nested locks. The processor tracks a lock for elisionbeginning with the XACQUIRE prefixed HLE eligible instruction for thatlock and ending with the XRELEASE prefixed HLE eligible instruction forthat same lock. The processor can, at any one time, track up to aMAX_HLE_ELIDED_LOCKS number of locks. For example, if the implementationsupports a MAX_HLE_ELIDED_LOCKS value of two and if the programmer neststhree HLE identified critical sections (by performing XACQUIRE prefixedHLE eligible instructions on three distinct locks without performing anintervening XRELEASE prefixed HLE eligible instruction on any one of thelocks), then the first two locks will be elided, but the third won't beelided (but will be added to the transaction's writeset). However, theexecution will still continue transactionally. Once an XRELEASE for oneof the two elided locks is encountered, a subsequent lock acquiredthrough the XACQUIRE prefixed HLE eligible instruction will be elided.

The processor attempts to commit the HLE execution when all elidedXACQUIRE and XRELEASE pairs have been matched, the nesting count goes tozero, and the locks have satisfied requirements. If execution cannotcommit atomically, then execution transitions to a non-transactionalexecution without elision as if the first instruction did not have anXACQUIRE prefix.

RTM Nesting

Programmers can nest RTM regions up to an implementation specificMAX_RTM_NEST_COUNT. The logical processor tracks the nesting countinternally but this count is not available to software. An XBEGINinstruction increments the nesting count, and an XEND instructiondecrements the nesting count. The logical processor attempts to commitonly if the nesting count becomes zero. A transactional abort occurs ifthe nesting count exceeds MAX_RTM_NEST_COUNT.

Nesting HLE and RTM

HLE and RTM provide two alternative software interfaces to a commontransactional execution capability. Transactional processing behavior isimplementation specific when HLE and RTM are nested together, e.g., HLEis inside RTM or RTM is inside HLE. However, in all cases, theimplementation will maintain HLE and RTM semantics. An implementationmay choose to ignore HLE hints when used inside RTM regions, and maycause a transactional abort when RTM instructions are used inside HLEregions. In the latter case, the transition from transactional tonon-transactional execution occurs seamlessly since the processor willre-execute the HLE region without actually doing elision, and thenexecute the RTM instructions.

Abort Status Definition

RTM uses the EAX register to communicate abort status to software.Following an RTM abort the EAX register has the following definition.

TABLE 1 RTM Abort Status Definition EAX Register Bit Position Meaning 0Set if abort caused by XABORT instruction 1 If set, the transaction maysucceed on retry, this bit is always clear if bit 0 is set 2 Set ifanother logical processor conflicted with a memory address that was partof the transaction that aborted 3 Set if an internal buffer overflowed 4Set if a debug breakpoint was hit 5 Set if an abort occurred duringexecution of a nested transaction 23:6 Reserved 31-24 XABORT argument(only valid if bit 0 set, otherwise reserved)

The EAX abort status for RTM only provides causes for aborts. It doesnot by itself encode whether an abort or commit occurred for the RTMregion. The value of EAX can be 0 following an RTM abort. For example, aCPUID instruction when used inside an RTM region causes a transactionalabort and may not satisfy the requirements for setting any of the EAXbits. This may result in an EAX value of 0.

RTM Memory Ordering

A successful RTM commit causes all memory operations in the RTM regionto appear to execute atomically. A successfully committed RTM regionconsisting of an XBEGIN followed by an XEND, even with no memoryoperations in the RTM region, has the same ordering semantics as a LOCKprefixed instruction.

The XBEGIN instruction does not have fencing semantics. However, if anRTM execution aborts, then all memory updates from within the RTM regionare discarded and are not made visible to any other logical processor.

RTM-Enabled Debugger Support

By default, any debug exception inside an RTM region will cause atransactional abort and will redirect control flow to the fallbackinstruction address with architectural state recovered and bit 4 in EAXset. However, to allow software debuggers to intercept execution ondebug exceptions, the RTM architecture provides additional capability.

If bit 11 of DR7 and bit 15 of the IA32_DEBUGCTL_MSR are both 1, any RTMabort due to a debug exception (#DB) or breakpoint exception (#BP)causes execution to roll back and restart from the XBEGIN instructioninstead of the fallback address. In this scenario, the EAX register willalso be restored back to the point of the XBEGIN instruction.

Programming Considerations

Typical programmer-identified regions are expected to transactionallyexecute and commit successfully. However, Intel TSX does not provide anysuch guarantee. A transactional execution may abort for many reasons. Totake full advantage of the transactional capabilities, programmersshould follow certain guidelines to increase the probability of theirtransactional execution committing successfully.

This section discusses various events that may cause transactionalaborts. The architecture ensures that updates performed within atransaction that subsequently aborts execution will never becomevisible. Only committed transactional executions initiate an update tothe architectural state. Transactional aborts never cause functionalfailures and only affect performance.

Instruction Based Considerations

Programmers can use any instruction safely inside a transaction (HLE orRTM) and can use transactions at any privilege level. However, someinstructions will always abort the transactional execution and causeexecution to seamlessly and safely transition to a non-transactionalpath.

Intel TSX allows for most common instructions to be used insidetransactions without causing aborts. The following operations inside atransaction do not typically cause an abort:

-   -   Operations on the instruction pointer register, general purpose        registers (GPRs) and the status flags (CF, OF, SF, PF, AF, and        ZF); and    -   Operations on XMM and YMM registers and the MXCSR register.

However, programmers must be careful when intermixing SSE and AVXoperations inside a transactional region. Intermixing SSE instructionsaccessing XMM registers and AVX instructions accessing YMM registers maycause transactions to abort. Programmers may use REP/REPNE prefixedstring operations inside transactions. However, long strings may causeaborts. Further, the use of CLD and STD instructions may cause aborts ifthey change the value of the DF flag. However, if DF is 1, the STDinstruction will not cause an abort. Similarly, if DF is 0, then the CLDinstruction will not cause an abort.

Instructions not enumerated here as causing abort when used inside atransaction will typically not cause a transaction to abort (examplesinclude but are not limited to MFENCE, LFENCE, SFENCE, RDTSC, RDTSCP,etc.).

The following instructions will abort transactional execution on anyimplementation:

-   -   XABORT    -   CPUID    -   PAUSE

In addition, in some implementations, the following instructions mayalways cause transactional aborts. These instructions are not expectedto be commonly used inside typical transactional regions. However,programmers must not rely on these instructions to force a transactionalabort, since whether they cause transactional aborts is implementationdependent.

-   -   Operations on X87 and MMX architecture state. This includes all        MMX and X87 instructions, including the FXRSTOR and FXSAVE        instructions.    -   Update to non-status portion of EFLAGS: CLI, STI, POPFD, POPFQ,        CLTS.    -   Instructions that update segment registers, debug registers        and/or control registers: MOV to DS/ES/FS/GS/SS, POP        DS/ES/FS/GS/SS, LDS, LES, LFS, LGS, LSS, SWAPGS, WRFSBASE,        WRGSBASE, LGDT, SGDT, LIDT, SIDT, LLDT, SLDT, LTR, STR, Far        CALL, Far JMP, Far RET, IRET, MOV to DRx, MOV to        CR0/CR2/CR3/CR4/CR8 and LMSW.    -   Ring transitions: SYSENTER, SYSCALL, SYSEXIT, and SYSRET.    -   TLB and Cacheability control: CLFLUSH, INVD, WBINVD, INVLPG,        INVPCID, and memory instructions with a non-temporal hint        (MOVNTDQA, MOVNTDQ, MOVNTI, MOVNTPD, MOVNTPS, and MOVNTQ).    -   Processor state save: XSAVE, XSAVEOPT, and XRSTOR.    -   Interrupts: INTn, INTO.    -   IO: IN, INS, REP INS, OUT, OUTS, REP OUTS and their variants.    -   VMX: VMPTRLD, VMPTRST, VMCLEAR, VMREAD, VMWRITE, VMCALL,        VMLAUNCH, VMRESUME, VMXOFF, VMXON, INVEPT, and INVVPID.    -   SMX: GETSEC.    -   UD2, RSM, RDMSR, WRMSR, HLT, MONITOR, MWAIT, XSETBV, VZEROUPPER,        MASKMOVQ, and V/MASKMOVDQU.        Runtime Considerations

In addition to the instruction-based considerations, runtime events maycause transactional execution to abort. These may be due to data accesspatterns or micro-architectural implementation features. The followinglist is not a comprehensive discussion of all abort causes.

Any fault or trap in a transaction that must be exposed to software willbe suppressed. Transactional execution will abort and execution willtransition to a non-transactional execution, as if the fault or trap hadnever occurred. If an exception is not masked, then that un-maskedexception will result in a transactional abort and the state will appearas if the exception had never occurred.

Synchronous exception events (#DE, #OF, #NP, #SS, #GP, #BR, #UD, #AC,#XF, #PF, #NM, #TS, #MF, #DB, #BP/INT3) that occur during transactionalexecution may cause an execution not to commit transactionally, andrequire a non-transactional execution. These events are suppressed as ifthey had never occurred. With HLE, since the non-transactional code pathis identical to the transactional code path, these events will typicallyre-appear when the instruction that caused the exception is re-executednon-transactionally, causing the associated synchronous events to bedelivered appropriately in the non-transactional execution. Asynchronousevents (NMI, SMI, INTR, IPI, PMI, etc.) occurring during transactionalexecution may cause the transactional execution to abort and transitionto a non-transactional execution. The asynchronous events will be pendedand handled after the transactional abort is processed.

Transactions only support write-back cacheable memory type operations. Atransaction may always abort if the transaction includes operations onany other memory type. This includes instruction fetches to UC memorytype.

Memory accesses within a transactional region may require the processorto set the Accessed and Dirty flags of the referenced page table entry.The behavior of how the processor handles this is implementationspecific. Some implementations may allow the updates to these flags tobecome externally visible even if the transactional region subsequentlyaborts. Some Intel TSX implementations may choose to abort thetransactional execution if these flags need to be updated. Further, aprocessor's page-table walk may generate accesses to its owntransactionally written but uncommitted state. Some Intel TSXimplementations may choose to abort the execution of a transactionalregion in such situations. Regardless, the architecture ensures that, ifthe transactional region aborts, then the transactionally written statewill not be made architecturally visible through the behavior ofstructures such as TLBs.

Executing self-modifying code transactionally may also causetransactional aborts. Programmers must continue to follow the Intelrecommended guidelines for writing self-modifying and cross-modifyingcode even when employing HLE and RTM. While an implementation of RTM andHLE will typically provide sufficient resources for executing commontransactional regions, implementation constraints and excessive sizesfor transactional regions may cause a transactional execution to abortand transition to a non-transactional execution. The architectureprovides no guarantee of the amount of resources available to dotransactional execution and does not guarantee that a transactionalexecution will ever succeed.

Conflicting requests to a cache line accessed within a transactionalregion may prevent the transaction from executing successfully. Forexample, if logical processor P0 reads line A in a transactional regionand another logical processor P1 writes line A (either inside or outsidea transactional region) then logical processor P0 may abort if logicalprocessor P1's write interferes with processor P0's ability to executetransactionally.

Similarly, if P0 writes line A in a transactional region and P1 reads orwrites line A (either inside or outside a transactional region), then P0may abort if P1's access to line A interferes with P0's ability toexecute transactionally. In addition, other coherence traffic may attimes appear as conflicting requests and may cause aborts. While thesefalse conflicts may happen, they are expected to be uncommon. Theconflict resolution policy to determine whether P0 or P1 aborts in theabove scenarios is implementation specific.

Generic Transaction Execution Embodiments:

According to “ARCHITECTURES FOR TRANSACTIONAL MEMORY”, a dissertationsubmitted to the Department of Computer Science and the Committee onGraduate Studies of Stanford University in partial fulfillment of therequirements for the Degree of Doctor of Philosophy, by Austen McDonald,June 2009, incorporated by reference herein in its entirety,fundamentally, there are three mechanisms needed to implement an atomicand isolated transactional region: versioning, conflict detection, andcontention management.

To make a transactional code region appear atomic, all the modificationsperformed by that transactional code region must be stored and keptisolated from other transactions until commit time. The system does thisby implementing a versioning policy. Two versioning paradigms exist:eager and lazy. An eager versioning system stores newly generatedtransactional values in place and stores previous memory values on theside, in what is called an undo-log. A lazy versioning system stores newvalues temporarily in what is called a write buffer, copying them tomemory only on commit. In either system, the cache is used to optimizestorage of new versions.

To ensure that transactions appear to be performed atomically, conflictsmust be detected and resolved. The two systems, i.e., the eager and lazyversioning systems, detect conflicts by implementing a conflictdetection policy, either optimistic or pessimistic. An optimistic systemexecutes transactions in parallel, checking for conflicts only when atransaction commits. A pessimistic system checks for conflicts at eachload and store. Similar to versioning, conflict detection also uses thecache, marking each line as either part of the read-set, part of thewrite-set, or both. The two systems resolve conflicts by implementing acontention management policy. Many contention management policies exist,some are more appropriate for optimistic conflict detection and some aremore appropriate for pessimistic. Described below are some examplepolicies.

Since each transactional memory (TM) system needs both versioningdetection and conflict detection, these options give rise to fourdistinct TM designs: Eager-Pessimistic (EP), Eager-Optimistic (EO),Lazy-Pessimistic (LP), and Lazy-Optimistic (LO). Table 2 brieflydescribes all four distinct TM designs.

FIGS. 1 and 2 depict an example of a multicore TM environment. FIG. 1shows many TM-enabled CPUs (CPU1 114 a, CPU2 114 b, etc.) on one die100, connected with an interconnect 122, under management of aninterconnect control 120 a, 120 b. Each CPU 114 a, 114 b (also known asa Processor) may have a split cache consisting of an Instruction Cache116 a, 116 b for caching instructions from memory to be executed and aData Cache 118 a, 118 b with TM support for caching data (operands) ofmemory locations to be operated on by the CPU 114, 114 b (in FIG. 1,each CPU 114 a, 114 b and its associated caches are referenced as 112 a,112 b). In an implementation, caches of multiple dies 100 areinterconnected to support cache coherency between the caches of themultiple dies 100. In an implementation, a single cache, rather than thesplit cache is employed holding both instructions and data. Inimplementations, the CPU caches are one level of caching in ahierarchical cache structure. For example, each die 100 may employ ashared cache 124 to be shared amongst all the CPUs on the die 100. Inanother implementation, each die may have access to a shared cache 124,shared amongst all the processors of all the dies 100.

FIG. 2 shows the details of an example transactional CPU 114, includingadditions to support TM. The transactional CPU (processor) 114 mayinclude hardware for supporting Register Checkpoints 126 and special TMRegisters 128. The transactional CPU cache may have the MESI bits 130,Tags 140 and Data 142 of a conventional cache but also, for example, Rbits 132 showing a line has been read by the CPU 114 while executing atransaction and W bits 138 showing a line has been written-to by the CPU114 while executing a transaction.

A key detail for programmers in any TM system is how non-transactionalaccesses interact with transactions. By design, transactional accessesare screened from each other using the mechanisms above. However, theinteraction between a regular, non-transactional load with a transactioncontaining a new value for that address must still be considered. Inaddition, the interaction between a non-transactional store with atransaction that has read that address must also be explored. These areissues of the database concept isolation.

A TM system is said to implement strong isolation, sometimes calledstrong atomicity, when every non-transactional load and store acts likean atomic transaction. Therefore, non-transactional loads cannot seeuncommitted data and non-transactional stores cause atomicity violationsin any transactions that have read that address. A system where this isnot the case is said to implement weak isolation, sometimes called weakatomicity.

Strong isolation is often more desirable than weak isolation due to therelative ease of conceptualization and implementation of strongisolation. Additionally, if a programmer has forgotten to surround someshared memory references with transactions, causing bugs, then withstrong isolation, the programmer will often detect that oversight usinga simple debug interface because the programmer will see anon-transactional region causing atomicity violations. Also, programswritten in one model may work differently on another model.

Further, strong isolation is often easier to support in hardware TM thanweak isolation. With strong isolation, since the coherence protocolalready manages load and store communication between processors,transactions can detect non-transactional loads and stores and actappropriately. To implement strong isolation in software TransactionalMemory (TM), non-transactional code must be modified to include read-and write-barriers; potentially crippling performance. Although greateffort has been expended to remove many un-needed barriers, suchtechniques are often complex and performance is typically far lower thanthat of hardware TMs.

TABLE 2 Transactional Memory Design Space VERSIONING Lazy Eager CONFLICTOptimistic Storing updates Not practical: waiting DETECTION in a writeto update memory buffer; detecting until commit time but conflicts atdetecting conflicts at commit time. access time guarantees wasted workand provides no advantage Pessimistic Storing updates Updating memory,in a write keeping old values buffer; detecting in undo log; conflictsat detecting conflicts access time. at access time.

Table 2 illustrates the fundamental design space of transactional memory(versioning and conflict detection).

Eager-Pessimistic (EP)

This first TM design described below is known as Eager-Pessimistic. AnEP system stores its write-set “in place” (hence the name “eager”) and,to support rollback, stores the old values of overwritten lines in an“undo log”. Processors use the W 138 and R 132 cache bits to track readand write-sets and detect conflicts when receiving snooped loadrequests. Perhaps the most notable examples of EP systems in knownliterature are LogTM and UTM.

Beginning a transaction in an EP system is much like beginning atransaction in other systems: tm_begin( ) takes a register checkpoint,and initializes any status registers. An EP system also requiresinitializing the undo log, the details of which are dependent on the logformat, but often involve initializing a log base pointer to a region ofpre-allocated, thread-private memory, and clearing a log boundsregister.

Versioning: In EP, due to the way eager versioning is designed tofunction, the MESI 130 state transitions (cache line indicatorscorresponding to Modified, Exclusive, Shared, and Invalid code states)are left mostly unchanged. Outside of a transaction, the MESI 130 statetransitions are left completely unchanged. When reading a line inside atransaction, the standard coherence transitions apply (S (Shared)→S, I(Invalid)→S, or I→E (Exclusive)), issuing a load miss as needed, but theR 132 (Read) bit is also set. Likewise, writing a line applies thestandard transitions (S→M, E→I, I→M), issuing a miss as needed, but alsosets the W 138 (Written) bit. The first time a line is written, the oldversion of the entire line is loaded then written to the undo log topreserve it in case the current transaction aborts. The newly writtendata is then stored “in-place,” over the old data.

Conflict Detection: Pessimistic conflict detection uses coherencemessages exchanged on misses, or upgrades, to look for conflicts betweentransactions. When a read miss occurs within a transaction, otherprocessors receive a load request; but they ignore the request if theydo not have the needed line. If the other processors have the neededline non-speculatively or have the line R 132, they downgrade that lineto S, and in certain cases issue a cache-to-cache transfer if they havethe line in MESI's 130 M or E state. However, if the cache has the lineW 138, then a conflict is detected between the two transactions andadditional action(s) must be taken.

Similarly, when a transaction seeks to upgrade a line from shared tomodified (on a first write), the transaction issues an exclusive loadrequest, which is also used to detect conflicts. If a receiving cachehas the line non-speculatively, then the line is invalidated, and incertain cases a cache-to-cache transfer (M or E states) is issued. But,if the line is R 132 or W 138, a conflict is detected.

Validation: Because conflict detection is performed on every load, atransaction always has exclusive access to its own write-set. Therefore,validation does not require any additional work.

Commit: Since eager versioning stores the new version of data items inplace, the commit process simply clears the W 138 and R 132 bits anddiscards the undo log.

Abort: When a transaction rolls back, the original version of each cacheline in the undo log must be restored, a process called “unrolling” or“applying” the log. This is done during tm_discard( ) and must be atomicwith regard to other transactions. Specifically, the write-set muststill be used to detect conflicts: this transaction has the only correctversion of lines in its undo log, and requesting transactions must waitfor the correct version to be restored from that log. Such a log can beapplied using a hardware state machine or software abort handler.

Eager-Pessimistic has the characteristics of: Commit is simple and sinceit is in-place, very fast. Similarly, validation is a no-op. Pessimisticconflict detection detects conflicts early, thereby reducing the numberof “doomed” transactions. For example, if two transactions are involvedin a Write-After-Read dependency, then that dependency is detectedimmediately in pessimistic conflict detection. However, in optimisticconflict detection such conflicts are not detected until the writercommits.

Eager-Pessimistic also has the characteristics of: As described above,the first time a cache line is written, the old value must be written tothe log, incurring extra cache accesses. Aborts are expensive as theyrequire undoing the log. For each cache line in the log, a load must beissued, perhaps going as far as main memory before continuing to thenext line. Pessimistic conflict detection also prevents certainserializable schedules from existing.

Additionally, because conflicts are handled as they occur, there is apotential for livelock and careful contention management mechanisms mustbe employed to guarantee forward progress.

Lazy-Optimistic (LO)

Another popular TM design is Lazy-Optimistic (LO), which stores itswrite-set in a “write buffer” or “redo log” and detects conflicts atcommit time (still using the R 132 and W 138 bits).

Versioning: Just as in the EP system, the MESI protocol of the LO designis enforced outside of the transactions. Once inside a transaction,reading a line incurs the standard MESI transitions but also sets the R132 bit. Likewise, writing a line sets the W 138 bit of the line, buthandling the MESI transitions of the LO design is different from that ofthe EP design. First, with lazy versioning, the new versions of writtendata are stored in the cache hierarchy until commit while othertransactions have access to old versions available in memory or othercaches. To make available the old versions, dirty lines (M lines) mustbe evicted when first written by a transaction. Second, no upgrademisses are needed because of the optimistic conflict detection feature:if a transaction has a line in the S state, it can simply write to itand upgrade that line to an M state without communicating the changeswith other transactions because conflict detection is done at committime.

Conflict Detection and Validation: To validate a transaction and detectconflicts, LO communicates the addresses of speculatively modified linesto other transactions only when it is preparing to commit. Onvalidation, the processor sends one, potentially large, network packetcontaining all the addresses in the write-set. Data is not sent, butleft in the cache of the committer and marked dirty (M). To build thispacket without searching the cache for lines marked W, a simple bitvector is used, called a “store buffer,” with one bit per cache line totrack these speculatively modified lines. Other transactions use thisaddress packet to detect conflicts: if an address is found in the cacheand the R 132 and/or W 138 bits are set, then a conflict is initiated.If the line is found but neither R 132 nor W 138 is set, then the lineis simply invalidated, which is similar to processing an exclusive load.

To support transaction atomicity, these address packets must be handledatomically, i.e., no two address packets may exist at once with the sameaddresses. In an LO system, this can be achieved by simply acquiring aglobal commit token before sending the address packet. However, atwo-phase commit scheme could be employed by first sending out theaddress packet, collecting responses, enforcing an ordering protocol(perhaps oldest transaction first), and committing once all responsesare satisfactory.

Commit: Once validation has occurred, commit needs no special treatment:simply clear W 138 and R 132 bits and the store buffer. Thetransaction's writes are already marked dirty in the cache and othercaches' copies of these lines have been invalidated via the addresspacket. Other processors can then access the committed data through theregular coherence protocol.

Abort: Rollback is equally easy: because the write-set is containedwithin the local caches, these lines can be invalidated, then clear W138 and R132 bits and the store buffer. The store buffer allows W linesto be found to invalidate without the need to search the cache.

Lazy-Optimistic has the characteristics of: Aborts are very fast,requiring no additional loads or stores and making only local changes.More serializable schedules can exist than found in EP, which allows anLO system to more aggressively speculate that transactions areindependent, which can yield higher performance. Finally, the latedetection of conflicts can increase the likelihood of forward progress.

Lazy-Optimistic also has the characteristics of: Validation takes globalcommunication time proportional to size of write set. Doomedtransactions can waste work since conflicts are detected only at committime.

Lazy-Pessimistic (LP)

Lazy-Pessimistic (LP) represents a third TM design option, sittingsomewhere between EP and LO: storing newly written lines in a writebuffer but detecting conflicts on a per access basis.

Versioning: Versioning is similar but not identical to that of LO:reading a line sets its R 132 bit, writing a line sets its W 138 bit,and a store buffer is used to track W lines in the cache. Also, dirty(M) lines must be evicted when first written by a transaction, just asin LO. However, since conflict detection is pessimistic, load exclusivesmust be performed when upgrading a transactional line from I, S→M, whichis unlike LO.

Conflict Detection: LP's conflict detection operates the same as EP's:using coherence messages to look for conflicts between transactions.

Validation: Like in EP, pessimistic conflict detection ensures that atany point, a running transaction has no conflicts with any other runningtransaction, so validation is a no-op.

Commit: Commit needs no special treatment: simply clear W 138 and R 132bits and the store buffer, like in LO.

Abort: Rollback is also like that of LO: simply invalidate the write-setusing the store buffer and clear the W and R bits and the store buffer.

Eager-Optimistic (EO)

The LP has the characteristics of: Like LO, aborts are very fast. LikeEP, the use of pessimistic conflict detection reduces the number of“doomed” transactions Like EP, some serializable schedules are notallowed and conflict detection must be performed on each cache miss.

The final combination of versioning and conflict detection isEager-Optimistic (EO). EO may be a less than optimal choice for hardwareTM systems: since new transactional versions are written in-place, othertransactions have no choice but to notice conflicts as they occur (i.e.,as cache misses occur). But since EO waits until commit time to detectconflicts, those transactions become “zombies,” continuing to execute,wasting resources, yet are “doomed” to abort.

EO has proven to be useful in software TMs and is implemented byBartok-STM and McRT. A lazy versioning software TM needs to check itswrite buffer on each read to ensure that it is reading the most recentvalue. Since the write buffer is not a hardware structure, this isexpensive, hence the preference for write-in-place eager versioning.Additionally, since checking for conflicts is also expensive in asoftware TM, optimistic conflict detection offers the advantage ofperforming this operation in bulk.

Contention Management

How a transaction rolls back once the system has decided to abort thattransaction has been described above, but, since a conflict involves twotransactions, the topics of which transaction should abort, how thatabort should be initiated, and when should the aborted transaction beretried need to be explored. These are topics that are addressed byContention Management (CM), a key component of transactional memory.Described below are policies regarding how the systems initiate abortsand the various established methods of managing which transactionsshould abort in a conflict.

Contention Management Policies

A Contention Management (CM) Policy is a mechanism that determines whichtransaction involved in a conflict should abort and when the abortedtransaction should be retried. For example, it is often the case thatretrying an aborted transaction immediately does not lead to the bestperformance. Conversely, employing a back-off mechanism, which delaysthe retrying of an aborted transaction, can yield better performance.Software TMs first grappled with finding the best contention managementpolicies and many of the policies outlined below were originallydeveloped for software TMs.

CM Policies draw on a number of measures to make decisions, includingages of the transactions, size of read- and write-sets, the number ofprevious aborts, etc. The combinations of measures to make suchdecisions are endless, but certain combinations are described below,roughly in order of increasing complexity.

To establish some nomenclature, first note that in a conflict there aretwo sides: the attacker and the defender. The attacker is thetransaction requesting access to a shared memory location. Inpessimistic conflict detection, the attacker is the transaction issuingthe load or load exclusive. In optimistic, the attacker is thetransaction attempting to validate. The defender in both cases is thetransaction receiving the attacker's request.

An Aggressive CM Policy immediately and always retries either theattacker or the defender. In LO, Aggressive means that the attackeralways wins, and so Aggressive is sometimes called committer wins. Sucha policy was used for the earliest LO systems. In the case of EP,Aggressive can be either defender wins or attacker wins.

Restarting a conflicting transaction that will immediately experienceanother conflict is bound to waste work—namely interconnect bandwidthrefilling cache misses. A Polite CM Policy employs exponential backoff(but linear could also be used) before restarting conflicts. To preventstarvation, a situation where a process does not have resourcesallocated to it by the scheduler, the exponential backoff greatlyincreases the odds of transaction success after some n retries.

Another approach to conflict resolution is to randomly abort theattacker or defender (a policy called Randomized). Such a policy may becombined with a randomized backoff scheme to avoid unneeded contention.

However, making random choices, when selecting a transaction to abort,can result in aborting transactions that have completed “a lot of work”,which can waste resources. To avoid such waste, the amount of workcompleted on the transaction can be taken into account when determiningwhich transaction to abort. One measure of work could be a transaction'sage. Other methods include Oldest, Bulk TM, Size Matters, Karma, andPolka. Oldest is a simple timestamp method that aborts the youngertransaction in a conflict. Bulk TM uses this scheme. Size Matters islike Oldest but instead of transaction age, the number of read/writtenwords is used as the priority, reverting to Oldest after a fixed numberof aborts. Karma is similar, using the size of the write-set aspriority. Rollback then proceeds after backing off a fixed amount oftime. Aborted transactions keep their priorities after being aborted(hence the name Karma). Polka works like Karma but instead of backingoff a predefined amount of time, it backs off exponentially more eachtime.

Since aborting wastes work, it is logical to argue that stalling anattacker until the defender has finished their transaction would lead tobetter performance. Unfortunately, such a simple scheme easily leads todeadlock.

Deadlock avoidance techniques can be used to solve this problem. Greedyuses two rules to avoid deadlock. The first rule is, if a firsttransaction, T1, has lower priority than a second transaction, T0, or ifT1 is waiting for another transaction, then T1 aborts when conflictingwith T0. The second rule is, if T1 has higher priority than T0 and isnot waiting, then T0 waits until T1 commits, aborts, or starts waiting(in which case the first rule is applied). Greedy provides someguarantees about time bounds for executing a set of transactions. One EPdesign (LogTM) uses a CM policy similar to Greedy to achieve stallingwith conservative deadlock avoidance.

Example MESI coherency rules provide for four possible states in which acache line of a multiprocessor cache system may reside, M, E, S, and I,defined as follows:

Modified (M): The cache line is present only in the current cache, andis dirty; it has been modified from the value in main memory. The cacheis required to write the data back to main memory at some time in thefuture, before permitting any other read of the (no longer valid) mainmemory state. The write-back changes the line to the Exclusive state.

Exclusive (E): The cache line is present only in the current cache, butis clean; it matches main memory. It may be changed to the Shared stateat any time, in response to a read request. Alternatively, it may bechanged to the Modified state when writing to it.

Shared (S): Indicates that this cache line may be stored in other cachesof the machine and is “clean”; it matches the main memory. The line maybe discarded (changed to the Invalid state) at any time.

Invalid (I): Indicates that this cache line is invalid (unused).

TM coherency status indicators (R 132, W 138) may be provided for eachcache line, in addition to, or encoded in the MESI coherency bits. An R132 indicator indicates the current transaction has read from the dataof the cache line, and a W 138 indicator indicates the currenttransaction has written to the data of the cache line.

In another aspect of TM design, a system is designed using transactionalstore buffers. U.S. Pat. No. 6,349,361 titled “Methods and Apparatus forReordering and Renaming Memory References in a Multiprocessor ComputerSystem,” filed Mar. 31, 2000 and incorporated by reference herein in itsentirety, teaches a method for reordering and renaming memory referencesin a multiprocessor computer system having at least a first and a secondprocessor. The first processor has a first private cache and a firstbuffer, and the second processor has a second private cache and a secondbuffer. The method includes the steps of, for each of a plurality ofgated store requests received by the first processor to store a datum,exclusively acquiring a cache line that contains the datum by the firstprivate cache, and storing the datum in the first buffer. Upon the firstbuffer receiving a load request from the first processor to load aparticular datum, the particular datum is provided to the firstprocessor from among the data stored in the first buffer based on anin-order sequence of load and store operations. Upon the first cachereceiving a load request from the second cache for a given datum, anerror condition is indicated and a current state of at least one of theprocessors is reset to an earlier state when the load request for thegiven datum corresponds to the data stored in the first buffer.

The main implementation components of one such transactional memoryfacility are a transaction-backup register file for holdingpre-transaction GR (general register) content, a cache directory totrack the cache lines accessed during the transaction, a store cache tobuffer stores until the transaction ends, and firmware routines toperform various complex functions. In this section a detailedimplementation is described.

IBM zEnterprise EC12 Enterprise Server Embodiment

The IBM zEnterprise EC12 enterprise server introduces transactionalexecution (TX) in transactional memory, and is described in part in apaper, “Transactional Memory Architecture and Implementation for IBMSystem z” of Proceedings Pages 25-36 presented at MICRO-45, 1-5 Dec.2012, Vancouver, British Columbia, Canada, available from IEEE ComputerSociety Conference Publishing Services (CPS), which is incorporated byreference herein in its entirety.

Table 3 shows an example transaction. Transactions started with TBEGINare not assured to ever successfully complete with TEND, since they canexperience an aborting condition at every attempted execution, e.g., dueto repeating conflicts with other CPUs. This requires that the programsupport a fallback path to perform the same operationnon-transactionally, e.g., by using traditional locking schemes. Thisputs significant burden on the programming and software verificationteams, especially where the fallback path is not automatically generatedby a reliable compiler.

TABLE 3 Example Transaction Code LHI R0,0 *initialize retry count=0 loopTBEGIN *begin transaction JNZ abort *go to abort code if CC1=0 LT R1,lock *load and test the fallback lock JNZ lckbzy *branch if lock busy .. . perform operation . . . TEND *end transaction . . . . . . . . . . .. lckbzy TABORT *abort if lock busy; this *resumes after TBEGIN abort JOfallback *no retry if CC=3 AHI R0, 1 *increment retry count CIJNL R0,6,fallback *give up after 6 attempts PPA R0, TX *random delay based onretry count . . . potentially wait for lock to become free . . . J loop*jump back to retry fallback OBTAIN lock *using Compare&Swap . . .perform operation . . . RELEASE lock . . . . . . . . . . . .

The requirement of providing a fallback path for aborted TransactionExecution (TX) transactions can be onerous. Many transactions operatingon shared data structures are expected to be short, touch only a fewdistinct memory locations, and use simple instructions only. For thosetransactions, the IBM zEnterprise EC12 introduces the concept ofconstrained transactions; under normal conditions, the CPU 114 assuresthat constrained transactions eventually end successfully, albeitwithout giving a strict limit on the number of necessary retries. Aconstrained transaction starts with a TBEGINC instruction and ends witha regular TEND. Implementing a task as a constrained or non-constrainedtransaction typically results in very comparable performance, butconstrained transactions simplify software development by removing theneed for a fallback path. IBM's Transactional Execution architecture isfurther described in z/Architecture, Principles of Operation, TenthEdition, SA22-7832-09 published September 2012 from IBM, incorporated byreference herein in its entirety.

A constrained transaction starts with the TBEGINC instruction. Atransaction initiated with TBEGINC must follow a list of programmingconstraints; otherwise the program takes a non-filterableconstraint-violation interruption. Exemplary constraints may include,but not be limited to: the transaction can execute a maximum of 32instructions, all instruction text must be within 256 consecutive bytesof memory; the transaction contains only forward-pointing relativebranches (i.e., no loops or subroutine calls); the transaction canaccess a maximum of 4 aligned octowords (an octoword is 32 bytes) ofmemory; and restriction of the instruction-set to exclude complexinstructions like decimal or floating-point operations. The constraintsare chosen such that many common operations like doubly linkedlist-insert/delete operations can be performed, including the verypowerful concept of atomic compare-and-swap targeting up to 4 alignedoctowords. At the same time, the constraints were chosen conservativelysuch that future CPU implementations can assure transaction successwithout needing to adjust the constraints, since that would otherwiselead to software incompatibility.

TBEGINC mostly behaves like XBEGIN in TSX or TBEGIN on IBM's zEC12servers, except that the floating-point register (FPR) control and theprogram interruption filtering fields do not exist and the controls areconsidered to be zero. On a transaction abort, the instruction addressis set back directly to the TBEGINC instead of to the instruction after,reflecting the immediate retry and absence of an abort path forconstrained transactions.

Nested transactions are not allowed within constrained transactions, butif a TBEGINC occurs within a non-constrained transaction it is treatedas opening a new non-constrained nesting level just like TBEGIN would.This can occur, e.g., if a non-constrained transaction calls asubroutine that uses a constrained transaction internally.

Since interruption filtering is implicitly off, all exceptions during aconstrained transaction lead to an interruption into the operatingsystem (OS). Eventual successful finishing of the transaction relies onthe capability of the OS to page-in the at most 4 pages touched by anyconstrained transaction. The OS must also ensure time-slices long enoughto allow the transaction to complete.

TABLE 4 Transaction Code Example TBEGINC *begin constrained transaction. . . perform operation . . . TEND *end transaction

Table 4 shows the constrained-transactional implementation of the codein Table 3, assuming that the constrained transactions do not interactwith other locking-based code. No lock testing is shown therefore, butcould be added if constrained transactions and lock-based code weremixed.

When failure occurs repeatedly, software emulation is performed usingmillicode as part of system firmware. Advantageously, constrainedtransactions have desirable properties because of the burden removedfrom programmers.

With reference to FIG. 3, the IBM zEnterprise EC12 processor introducedthe transactional execution facility. The processor can decode 3instructions per clock cycle; simple instructions are dispatched assingle micro-ops, and more complex instructions are cracked intomultiple micro-ops. The micro-ops (Uops 232 b) are written into aunified issue queue 216, from where they can be issued out-of-order. Upto two fixed-point, one floating-point, two load/store, and two branchinstructions can execute every cycle. A Global Completion Table (GCT)232 holds every micro-op and a transaction nesting depth (TND) 232 a.The GCT 232 is written in-order at decode time, tracks the executionstatus of each micro-op 232 b, and completes instructions when allmicro-ops 232 b of the oldest instruction group have successfullyexecuted.

The level 1 (L1) data cache 240 is a 96 KB (kilo-byte) 6-way associativecache with 256 byte cache-lines and 4 cycle use latency, coupled to aprivate 1 MB (mega-byte) 8-way associative 2nd-level (L2) data cache 268with 7 cycles use-latency penalty for L1 240 misses. L1 240 cache is thecache closest to a processor and Ln cache is a cache at the nth level ofcaching. Both L1 240 and L2 268 caches are store-through. Six cores oneach central processor (CP) chip share a 48 MB 3rd-level store-in cache,and six CP chips are connected to an off-chip 384 MB 4th-level cache,packaged together on a glass ceramic multi-chip module (MCM). Up to 4multi-chip modules (MCMs) can be connected to a coherent symmetricmulti-processor (SMP) system with up to 144 cores (not all cores areavailable to run customer workload).

Coherency is managed with a variant of the MESI protocol. Cache-linescan be owned read-only (shared) or exclusive; the L1 240 and L2 268 arestore-through and thus do not contain dirty lines. The L3 272 and L4caches (not shown) are store-in and track dirty states. Each cache isinclusive of all its connected lower level caches.

Coherency requests are called “cross interrogates” (XI) and are senthierarchically from higher level to lower-level caches, and between theL4s. When one core misses the L1 240 and L2 268 and requests the cacheline from its local L3 272, the L3 272 checks whether it owns the line,and if necessary sends an XI to the currently owning L2 268/L1 240 underthat L3 272 to ensure coherency, before it returns the cache line to therequestor. If the request also misses the L3 272, the L3 272 sends arequest to the L4 (not shown) which enforces coherency by sending XIs toall necessary L3s under that L4, and to the neighboring L4s. Then the L4responds to the requesting L3 which forwards the response to the L2268/L1 240.

Note that due to the inclusivity rule of the cache hierarchy, sometimescache lines are XI'ed from lower-level caches due to evictions onhigher-level caches caused by associativity overflows from requests toother cache lines. These XIs can be called “LRU XIs”, where LRU standsfor least recently used.

Making reference to yet another type of XI requests, Demote-XIstransition cache-ownership from exclusive into read-only state, andExclusive-XIs transition cache ownership from exclusive into invalidstate. Demote-XIs and Exclusive-XIs need a response back to the XIsender. The target cache can “accept” the XI, or send a “reject”response if it first needs to evict dirty data before accepting the XI.The L1 240/L2 268 caches are store through, but may reject demote-XIsand exclusive XIs if they have stores in their store queues that need tobe sent to L3 before downgrading the exclusive state. A rejected XI willbe repeated by the sender. Read-only-XIs are sent to caches that own theline read-only; no response is needed for such XIs since they cannot berejected. The details of the SMP protocol are similar to those describedfor the IBM z10 by P. Mak, C. Walters, and G. Strait, in “IBM System z10processor cache subsystem microarchitecture”, IBM Journal of Researchand Development, Vol 53:1, 2009, which is incorporated by referenceherein in its entirety.

Transactional Instruction Execution

FIG. 3 depicts example components of an example CPU environment 112,including a CPU 114 and caches/components with which it interacts (suchas those depicted in FIGS. 1 and 2). The instruction decode unit 208(IDU) keeps track of the current transaction nesting depth 212 (TND).When the IDU 208 receives a TBEGIN instruction, the nesting depth 212 isincremented, and conversely decremented on TEND instructions. Thenesting depth 212 is written into the GCT 232 for every dispatchedinstruction. When a TBEGIN or TEND is decoded on a speculative path thatlater gets flushed, the IDU's 208 nesting depth 212 is refreshed fromthe youngest GCT 232 entry that is not flushed. The transactional stateis also written into the issue queue 216 for consumption by theexecution units, mostly by the Load/Store Unit (LSU) 280, which also hasan effective address calculator 236 included in the LSU 280. The TBEGINinstruction may specify a transaction diagnostic block (TDB) forrecording status information, should the transaction abort beforereaching a TEND instruction.

Similar to the nesting depth, the IDU208/GCT 232 collaboratively trackthe access register/floating-point register (AR/FPR) modification masksthrough the transaction nest; the IDU 208 can place an abort requestinto the GCT 232 when an AR/FPR-modifying instruction is decoded and themodification mask blocks that. When the instruction becomesnext-to-complete, completion is blocked and the transaction aborts.Other restricted instructions are handled similarly, including TBEGIN ifdecoded while in a constrained transaction, or exceeding the maximumnesting depth.

An outermost TBEGIN is cracked into multiple micro-ops depending on theGR-Save-Mask; each micro-op 232 b (including, for example, uop 0, uop 1,and uop 2) will be executed by one of the two fixed point units (FXUs)220 to save a pair of GRs 228 into a special transaction-backup registerfile 224, that is used to later restore the GR 228 content in case of atransaction abort. Also the TBEGIN spawns micro-ops 232 b to perform anaccessibility test for the TDB if one is specified; the address is savedin a special purpose register for later usage in the abort case. At thedecoding of an outermost TBEGIN, the instruction address and theinstruction text of the TBEGIN are also saved in special purposeregisters for a potential abort processing later on.

TEND and NTSTG are single micro-op 232 b instructions; NTSTG(non-transactional store) is handled like a normal store except that itis marked as non-transactional in the issue queue 216 so that the LSU280 can treat it appropriately. TEND is a no-op at execution time, theending of the transaction is performed when TEND completes.

As mentioned, instructions that are within a transaction are marked assuch in the issue queue 216, but otherwise execute mostly unchanged; theLSU 280 performs isolation tracking as described in the next section.

Since decoding is in-order, and since the IDU 208 keeps track of thecurrent transactional state and writes it into the issue queue 216 alongwith every instruction from the transaction, execution of TBEGIN, TEND,and instructions before, within, and after the transaction can beperformed out-of order. It is even possible (though unlikely) that TENDis executed first, then the entire transaction, and lastly the TBEGINexecutes. Program order is restored through the GCT 232 at completiontime. The length of transactions is not limited by the size of the GCT232, since general purpose registers (GRs) 228 can be restored from thebackup register file 224.

During execution, the program event recording (PER) events are filteredbased on the Event Suppression Control, and a PER TEND event is detectedif enabled. Similarly, while in transactional mode, a pseudo-randomgenerator may be causing the random aborts as enabled by the TransactionDiagnostics Control.

Tracking for Transactional Isolation

The Load/Store Unit 280 tracks cache lines that were accessed duringtransactional execution, and triggers an abort if an XI from another CPU(or an LRU-XI) conflicts with the footprint. If the conflicting XI is anexclusive or demote XI, the LSU 280 rejects the XI back to the L3 272 inthe hope of finishing the transaction before the L3 272 repeats the XI.This “stiff-arming” is very efficient in highly contended transactions.In order to prevent hangs when two CPUs stiff-arm each other, aXI-reject counter is implemented, which triggers a transaction abortwhen a threshold is met.

The L1 cache directory 240 is traditionally implemented with staticrandom access memories (SRAMs). For the transactional memoryimplementation, the valid bits 244 (64 rows×6 ways) of the directoryhave been moved into normal logic latches, and are supplemented with twomore bits per cache line: the TX-read 248 and TX-dirty 252 bits.

The TX-read 248 bits are reset when a new outermost TBEGIN is decoded(which is interlocked against a prior still pending transaction). TheTX-read 248 bit is set at execution time by every load instruction thatis marked “transactional” in the issue queue. Note that this can lead toover-marking if speculative loads are executed, for example on amispredicted branch path. The alternative of setting the TX-read 248 bitat load completion time was too expensive for silicon area, sincemultiple loads can complete at the same time, requiring many read-portson the load-queue.

Stores execute the same way as in non-transactional mode, but atransaction mark is placed in the store queue (STQ) 260 entry of thestore instruction. At write-back time, when the data from the STQ 260 iswritten into the L1 240, the TX-dirty bit 252 in the L1-directory 256 isset for the written cache line. Store write-back into the L1 240 occursonly after the store instruction has completed, and at most one store iswritten back per cycle. Before completion and write-back, loads canaccess the data from the STQ 260 by means of store-forwarding; afterwrite-back, the CPU 114 (FIG. 2) can access the speculatively updateddata in the L1 240. If the transaction ends successfully, the TX-dirty252 bits of all cache-lines are cleared, and also the TX-marks of notyet written stores are cleared in the STQ 260, effectively turning thepending stores into normal stores.

On a transaction abort, all pending transactional stores are invalidatedfrom the STQ 260, even those already completed. All cache lines thatwere modified by the transaction in the L1 240, that is, have theTX-dirty 252 bit on, have their valid bits turned off, effectivelyremoving them from the L1 240 cache instantaneously.

The architecture requires that before completing a new instruction, theisolation of the transaction read- and write-set is maintained. Thisisolation is ensured by stalling instruction completion at appropriatetimes when XIs are pending; speculative out-of order execution isallowed, optimistically assuming that the pending XIs are to differentaddresses and not actually cause a transaction conflict. This designfits very naturally with the XI-vs-completion interlocks that areimplemented on prior systems to ensure the strong memory ordering thatthe architecture requires.

When the L1 240 receives an XI, L1 240 accesses the directory to checkvalidity of the XI'ed address in the L1 240, and if the TX-read 248 bitis active on the XI'ed line and the XI is not rejected, the LSU 280triggers an abort. When a cache line with active TX-read 248 bit isLRU'ed from the L1 240, a special LRU-extension vector remembers foreach of the 64 rows of the L1 240 that a TX-read line existed on thatrow. Since no precise address tracking exists for the LRU extensions,any non-rejected XI that hits a valid extension row the LSU 280 triggersan abort. Providing the LRU-extension effectively increases the readfootprint capability from the L1-size to the L2-size and associativity,provided no conflicts with other CPUs 114 (FIG. 1) against thenon-precise LRU-extension tracking causes aborts.

The store footprint is limited by the store cache size (the store cacheis discussed in more detail below) and thus implicitly by the L2 268size and associativity. No LRU-extension action needs to be performedwhen a TX-dirty 252 cache line is LRU'ed from the L1 240. Store Cache

In prior systems, since the L1 240 and L2 268 are store-through caches,every store instruction causes an L3 272 store access; with now 6 coresper L3 272 and further improved performance of each core, the store ratefor the L3 272 (and to a lesser extent for the L2 268) becomesproblematic for certain workloads. In order to avoid store queuingdelays a gathering store cache 264 had to be added, that combines storesto neighboring addresses before sending them to the L3 272.

For transactional memory performance, it is acceptable to invalidateevery TX-dirty 252 cache line from the L1 240 on transaction aborts,because the L2 268 cache is very close (7 cycles L1 240 miss penalty) tobring back the clean lines. However, it would be unacceptable forperformance (and silicon area for tracking) to have transactional storeswrite the L2 268 before the transaction ends and then invalidate alldirty L2 268 cache lines on abort (or even worse on the shared L3 272).

The two problems of store bandwidth and transactional memory storehandling can both be addressed with the gathering store cache 264. Thecache 264 is a circular queue of 64 entries, each entry holding 128bytes of data with byte-precise valid bits. In non-transactionaloperation, when a store is received from the LSU 280, the store cachechecks whether an entry exists for the same address, and if so gathersthe new store into the existing entry. If no entry exists, a new entryis written into the queue, and if the number of free entries falls undera threshold, the oldest entries are written back to the L2 268 and L3272 caches.

When a new outermost transaction begins, all existing entries in thestore cache are marked closed so that no new stores can be gathered intothem, and eviction of those entries to L2 268 and L3 272 is started.From that point on, the transactional stores coming out of the LSU 280STQ 260 allocate new entries, or gather into existing transactionalentries. The write-back of those stores into L2 268 and L3 272 isblocked, until the transaction ends successfully; at that pointsubsequent (post-transaction) stores can continue to gather intoexisting entries, until the next transaction closes those entries again.

The store cache is queried on every exclusive or demote XI, and causesan XI reject if the XI compares to any active entry. If the core is notcompleting further instructions while continuously rejecting XIs, thetransaction is aborted at a certain threshold to avoid hangs.

The LSU 280 requests a transaction abort when the store cache overflows.The LSU 280 detects this condition when it tries to send a new storethat cannot merge into an existing entry, and the entire store cache isfilled with stores from the current transaction. The store cache ismanaged as a subset of the L2 268: while transactionally dirty lines canbe evicted from the L1 240, they have to stay resident in the L2 268throughout the transaction. The maximum store footprint is thus limitedto the store cache size of 64×128 bytes, and it is also limited by theassociativity of the L2 268. Since the L2 268 is 8-way associative andhas 512 rows, it is typically large enough to not cause transactionaborts.

If a transaction aborts, the store cache is notified and all entriesholding transactional data are invalidated. The store cache also has amark per doubleword (8 bytes) whether the entry was written by a NTSTGinstruction—those doublewords stay valid across transaction aborts.

Millicode-Implemented Functions

Traditionally, IBM mainframe server processors contain a layer offirmware called millicode which performs complex functions like certainCISC instruction executions, interruption handling, systemsynchronization, and RAS. Millicode includes machine dependentinstructions as well as instructions of the instruction set architecture(ISA) that are fetched and executed from memory similarly toinstructions of application programs and the operating system (OS).Firmware resides in a restricted area of main memory that customerprograms cannot access. When hardware detects a situation that needs toinvoke millicode, the instruction fetching unit 204 switches into“millicode mode” and starts fetching at the appropriate location in themillicode memory area. Millicode may be fetched and executed in the sameway as instructions of the instruction set architecture (ISA), and mayinclude ISA instructions.

For transactional memory, millicode is involved in various complexsituations. Every transaction abort invokes a dedicated millicodesub-routine to perform the necessary abort steps. The transaction-abortmillicode starts by reading special-purpose registers (SPRs) holding thehardware internal abort reason, potential exception reasons, and theaborted instruction address, which millicode then uses to store a TDB ifone is specified. The TBEGIN instruction text is loaded from an SPR toobtain the GR-save-mask, which is needed for millicode to know which GRs238 to restore.

The CPU 114 (FIG. 2) supports a special millicode-only instruction toread out the backup-GRs 224 and copy them into the main GRs 228. TheTBEGIN instruction address is also loaded from an SPR to set the newinstruction address in the PSW to continue execution after the TBEGINonce the millicode abort sub-routine finishes. That PSW may later besaved as program-old PSW in case the abort is caused by a non-filteredprogram interruption.

The TABORT instruction may be millicode implemented; when the IDU 208decodes TABORT, it instructs the instruction fetch unit to branch intoTABORT's millicode, from which millicode branches into the common abortsub-routine.

The Extract Transaction Nesting Depth (ETND) instruction may also bemillicoded, since it is not performance critical; millicode loads thecurrent nesting depth out of a special hardware register and places itinto a GR 228. The PPA instruction is millicoded; it performs theoptimal delay based on the current abort count provided by software asan operand to PPA, and also based on other hardware internal state.

For constrained transactions, millicode may keep track of the number ofaborts. The counter is reset to 0 on successful TEND completion, or ifan interruption into the OS occurs (since it is not known if or when theOS will return to the program). Depending on the current abort count,millicode can invoke certain mechanisms to improve the chance of successfor the subsequent transaction retry. The mechanisms involve, forexample, successively increasing random delays between retries, andreducing the amount of speculative execution to avoid encounteringaborts caused by speculative accesses to data that the transaction isnot actually using. As a last resort, millicode can broadcast to otherCPUs 114 (FIG. 2) to stop all conflicting work, retry the localtransaction, before releasing the other CPUs 114 to continue normalprocessing. Multiple CPUs 114 must be coordinated to not causedeadlocks, so some serialization between millicode instances ondifferent CPUs 114 is required.

FIG. 4 illustrates an embodiment for salvaging a partially executedhardware transaction upon detection of a failure, in accordance withembodiments of the present disclosure. A general discussion ofembodiments of the present disclosure follows, prior to discussingparticulars of FIG. 4.

As discussed above, transactional semantics in transactional memorysystems may be enforced by tracking the memory locations read andwritten by each transaction. If multiple transactionally executinglogical processors access the same memory in a conflicting way, one ormore of the competing, or conflicting, transactions may be aborted. Forexample, two accesses of the same memory location may be conflicting ifat least one of the accesses is a write.

As further previously discussed, transactional memory systems implementtransactional semantics through a variety of techniques. Generally, agiven transactional memory system will include a mechanism formaintaining speculative state for a transaction that is being executed(e.g., speculative state may be maintained in-place, while rollbackinformation is preserved in an undo-log; or speculative state may bemaintained in a write buffer, while rollback information is preservedin-place, etc.). If one or more executing transactions exhausts aresource dedicated to the maintenance of speculative state, one or moreof the transactions may be aborted. For example, a transactional memorysystem that includes a hard limit on the number of nested transactionsmay abort one, some, or all nested transactions if the number of nestedtransactions exceeds the hard limit. In another example, a transactionalmemory system that includes a hard limit on the amount of storedspeculative state may abort one or more transactions if the amount ofspeculative state exceeds the hard limit (in this example, the hardlimit on the amount of speculative state may be based on, e.g., the sizeof the write buffer that maintains speculative state, etc.).

According to embodiments of the present disclosure, upon detection of afailure during an executing hardware transaction, instead of abortingthe executing transaction, the transactional memory system can salvagethe partially executed transaction by jumping to and executing anabout-to-fail handler. An about-to-fail handler determines speculativestate that is salvageable, commits any salvageable speculative state,and continues executing remaining instructions in the transaction. Bysalvaging the partially executed transaction, the transactional memorysystem thus preserves and utilizes speculative state that otherwisewould have been discarded upon abort.

In an exemplary embodiment, when a transaction is about to fail,hardware transfers control to software with an indication that thetransaction is about to fail. Then software determines salvageablespeculative state, commits, and continues executing the transaction.Further, hardware, such as an about-to-fail handler informationdeterminer 1060 in FIG. 10, provides a means to software to indicate theaddress of an about-to-fail handler. This can be done by providing anexplicit instruction to indicate such an address (e.g., arecord-about-to-fail-handler-address instruction, etc.). Or, hardwarecan use the same address for the failure handler (i.e., in an embodimentthat has both a failure handler and an about-to-fail handler) andprovide an indicator in, e.g., a condition register (e.g., salvagingregister(s) 1062, etc.), etc., that the transaction is about to fail buthas not yet actually failed. Information regarding the about-to-failhandler, such as an address, can be stored by the transactional memorysystem in a register (e.g., salvaging register(s) 1062, etc.). Hardware,for example, about-to-fail condition detector 1064 of FIG. 10, detectswhen a transaction is about to fail and transfers, for example, usinghardware transaction transferor 1066, control to the about-to-failhandler.

Software can use these techniques as follows to salvage computation inhardware transactions: Software can check a condition register todetermine if a transaction has failed, or is about to fail but has notyet actually failed. Alternately, software can use a means to determinethe location of the about-to-fail handler (e.g., therecord-about-to-fail-handler-address instruction records the location insalvaging register(s) 1062, etc.). In the about-to-fail handler,software determines if any of the partially executed transaction issalvageable, and commits any salvageable speculative state. Softwareproceeds to execute the remaining instructions in the transaction andupon completion of the transaction execution, commits speculative state.

In an embodiment, a transactional memory system (hardware), upondetecting an about-to-fail condition, e.g., by about-to-fail conditiondetector 1064, in a code region of an executing hardware transaction,transfers control, e.g., by hardware transaction transferor 1066, of thepartially executed hardware transaction to a recorded location of anabout-to-fail handler (software). Each of the following examples of anabout-to-fail condition may be detected by about-to-fail conditiondetector 1064 of FIG. 10. For example, the transaction is failing if ahard limit on the number of nested transactions will be exceeded uponexecution of the next instruction within the transactional code region(e.g., if the next instruction is a TBEGIN instruction, etc.). Foranother example, the transaction is failing if a hard limit on theamount of stored speculative state will be exceeded upon execution ofthe next instruction within the transactional code region (e.g., if thenext instruction involves a store into the write buffer that maintainsspeculative state, and the write buffer is already full, etc.). For yetanother example, the transaction is failing if it has entered into asharing conflict with another transaction. The transactional memorysystem can hold off the cause of failing the transaction, for example,if evaluating a next instruction in the hardware transaction determinesthe next instruction is about to cause its failure, the transactionalmemory system will stop execution of the instruction. Duringtransactional execution of the hardware transaction, the transactionalmemory system saves state information for a code region of the hardwaretransaction. State information can be saved in several ways, e.g., justonce in a hardware transaction, at several particular places in ahardware transaction, or after completion of each instruction in thehardware transaction, and may include information needed to determinewhether the hardware transaction is to be salvaged or to be aborted, orto complete transactional execution of the hardware transaction. Stateinformation may be saved in salvaging register(s) 1062 of FIG. 10.

The executing program (i.e., the executing software instructions withinthe about-to-fail handler) receives control of execution of thepartially executed transaction from a hardware component (block 419).The executing program reads state information to determine if thepartially executed transaction is salvageable, or to be aborted (block420). The executing program determines if the partially executedtransaction is salvageable (decision block 421). The executing programreads the state information, such as a state variable value, set duringexecution of the hardware transaction, to determine where execution ofthe transaction was interrupted. If none of the speculative state issalvageable (decision block 421, “no” branch), the transaction aborts(block 422). For example, if the state variable indicates thetransaction had just started executing instructions, the executingprogram determines any speculative state created is not salvageable, anddiscards, or destroys, the partially executed speculative state. Atransaction abort is issued by a “TABORT” or “XABORT” instruction, orgenerally, an “abort_transaction” instruction. If there is at least somespeculative state that is salvageable (decision block 421, “yes”branch), the executing program commits that speculative state (block424). For example, if the state variable indicates the transactioncompleted execution of the main operation portion of the hardwaretransaction, the executing program can salvage that portion and committhe speculative state of the main operation. Transaction stores of thepartially executed transaction can be committed to memory by issuing a“TEND” or “XEND” instruction, or generally, a “commit transaction”instruction. In an embodiment, prior to committing the partiallyexecuted transaction, the executing program executes instructions neededto take the transaction to a stable state.

The executing program executes code, or instructions, to compensate forthe incomplete part of the salvaged transaction (block 425). This can bedone non-transactionally, or using one or more new transactions. Anexemplary embodiment of the latter is discussed with reference to FIG.5.

FIG. 5 illustrates exemplary program code for implementing a softwarecomponent of the embodiment of FIG. 4, in accordance with embodiments ofthe present disclosure.

In an embodiment, a hardware transaction may operate on a data structureand include a main operation on the data structure, and secondaryactions such as updating statistics that are acceptable to be executedafter some delay from the main operation. Code section 500 illustratesan exemplary transaction construct for the hardware transaction, whichincludes setting a state variable to track the state of the transactionexecution. For example, in code section 500, before the main operation,the state variable is set to the value “starting,” after the mainoperation, the state variable is set to the value “done_with_main_op,”and after the reading statistics secondary action, the state variable isset to the value “done_reading_stats.” Code section 500 begins executingwith an instruction having a “transaction_begin” and a location of ahandler, which may be a failure handler, or an about-to-fail handler.The transactional memory system records the location of the handler, andbegins performing the main operations and secondary actions, setting thestate variable as discussed. If the transactional memory system detectsthe transaction is about to fail, as discussed with reference to FIG. 4,control of the transaction is transferred to a software component, suchas the about-to-fail handler illustrated in code section 510. Upon thetransfer of control, the state variable will hold a value according tothe last successful save. For example, if the transactional memorysystem detects the transaction is about to fail during the readingstatistics secondary action, the state variable will hold the“done_with_main_op” value.

Code section 510 illustrates exemplary instructions for an about-to-failhandler, including an initial instruction to ‘read state’, which allowsthe about-to-fail handler to read the state variable for determiningwhether the partially executed transaction is to be salvaged or to beaborted. If the state variable holds the value “starting,” then codesection 500 failed prior to completion of the main operation, and thetransaction is not salvageable (i.e., code section 510 performs atransaction abort instruction). Otherwise, the transaction issalvageable, and the speculative state of the partially executedtransaction is committed, as shown by the first “transaction_end”instruction in code section 510, and the transaction is brought to astable state. The about-to-fail handler then begins a new transactioncontaining duplicate instructions of the failed transaction, as well ascontaining a second check on the state variable to determine which ofthe duplicated instructions should be executed, in order to startexecution of the new hardware transaction at a point prior to, but near(i.e., at the point indicated by the state information), the point offailure in the failed transaction. For example, if the state variableholds the value “done_with_main_op,”, then code section 510 executes thereading statistics secondary action and then continues by executing theupdating statistics secondary action, but if it is not (i.e., if thestate variable holds the value “done_reading_stats”), then code section510 executes only the updating statistics secondary action. Upondetermining the new transaction completed, code section 510 commits thespeculative state at the second “transaction_end” instruction. In anembodiment, if the executing program determines the new transaction incode section 510 is about to fail, the executing program aborts the newtransaction. In an alternate embodiment, the remaining code instructionsfrom the failed transaction may be executed non-transactionally, forexample, by executing the next instruction after the point of failure inthe failed transaction, or prior to, but near the point of failure inthe failed transaction.

FIG. 6 illustrates an embodiment of the present disclosure for salvaginga partially executed hardware transaction. The embodiment saves stateinformation in a first code region of a first hardware transaction, thestate information usable to determine whether the first hardwaretransaction is to be salvaged or to be aborted (block 610). Theembodiment detects an about-to-fail condition during the transactionalexecution of the hardware transaction (block 612). If an about-to-failcondition is not detected, the embodiment continues to save stateinformation of the hardware transaction. If an about-to-fail conditionis detected, the illustrated embodiment executes an about-to-failhandler (block 614). The about-to-fail handler determines, using thesaved state information, whether the first hardware transaction is to besalvaged or to be aborted (block 616). If the first hardware transactionis to be aborted, the first hardware transaction is aborted (block 618).

As depicted in FIG. 6, if the first hardware transaction is to besalvaged, the illustrated embodiment uses the saved state information todetermine what portion of the first hardware transaction to salvage(block 620). The embodiment salvages a portion of the first hardwaretransaction by committing transaction stores to memory (block 622). Theillustrated embodiment starts execution of a second hardware transactionat a point in a second code region of the about-to-fail handlerindicated by the saved state information (block 624). The embodimentdetermines the execution completed (block 626) and commits speculativestate of the completed execution of the second hardware transaction(block 628).

As depicted in FIG. 7, the embodiment determines, using the saved stateinformation, whether the first hardware transaction is to be salvaged orto be aborted (at block 616 of FIG. 6), and then determines that thefirst hardware transaction, which includes a main operation portion andat least one secondary operation portion, is to be aborted if the mainoperation portion of the first hardware transaction did not executecompletely (block 720).

Upon determining the first hardware transaction is to be salvaged (block616 of FIG. 6), and salvaging a portion of the first hardwaretransaction by committing transaction stores to memory (block 622 ofFIG. 6), the illustrated embodiment can determine the hardwaretransaction can be completed non-transactionally (block 810) andcomplete the hardware transaction non-transactionally (block 820).

Referring to FIG. 9, the embodiment illustrated in FIG. 6 furtherdetects an about-to-fail condition during the transactional execution ofthe hardware transaction (block 612) by evaluating a next instructionsto determine if its execution will cause a failure (block 920), ordetermining that a limit on an amount of stored speculative state willbe exceeded upon execution of an instruction within the code region(block 940).

Referring now to FIG. 10, a functional block diagram of a computersystem in accordance with an embodiment of the present disclosure isshown. Computer system 1000 is only one example of a suitable computersystem and is not intended to suggest any limitation as to the scope ofuse or functionality of embodiments of the disclosure described herein.Regardless, computer system 1000 is capable of being implemented and/orperforming any of the functionality set forth hereinabove.

In computer system 1000 there is computer 1012, which is operationalwith numerous other general purpose or special purpose computing systemenvironments or configurations. Examples of well-known computingsystems, environments, and/or configurations that may be suitable foruse with computer 1012 include, but are not limited to, personalcomputer systems, server computer systems, thin clients, thick clients,handheld or laptop devices, multiprocessor systems, microprocessor-basedsystems, set top boxes, programmable consumer electronics, network PCs,minicomputer systems, mainframe computer systems, and distributed cloudcomputing environments that include any of the above systems or devices,and the like.

Computer 1012 may be described in the general context of computer systemexecutable instructions, such as program modules, being executed by acomputer system. Generally, program modules may include routines,programs, objects, components, logic, data structures, and so on thatperform particular tasks or implement particular abstract data types.Computer 1012 may be practiced in distributed cloud computingenvironments where tasks are performed by remote processing devices thatare linked through a communications network. In a distributed cloudcomputing environment, program modules may be located in both local andremote computer system storage media including memory storage devices.

As further shown in FIG. 10, computer 1012 in computer system 1000 isshown in the form of a general-purpose computing device. The componentsof computer 1012 may include, but are not limited to, one or moreprocessors or processing units 1016, memory 1028, and bus 1018 thatcouples various system components including memory 1028 to processingunit 1016. Processing units 1016 can, in various embodiments, includesome or all of CPU 114 a, 114 b of FIG. 1, transactional CPU environment112 of FIG. 2, and the processor of FIG. 3. Further, processing units1016 can, in various embodiments, include about-to-fail handlerinformation determiner 1060, some or all of salvaging register(s) 1062,about-to-fail condition detector 1064, and hardware transactiontransferor 1066, as discussed above in the context of FIG. 4.

Bus 1018 represents one or more of any of several types of busstructures, including a memory bus or memory controller, a peripheralbus, an accelerated graphics port, and a processor or local bus usingany of a variety of bus architectures. By way of example, and notlimitation, such architectures include Industry Standard Architecture(ISA) bus, Micro Channel Architecture (MCA) bus, Enhanced ISA (EISA)bus, Video Electronics Standards Association (VESA) local bus, andPeripheral Component Interconnect (PCI) bus.

Computer 1012 typically includes a variety of computer system readablemedia. Such media may be any available media that is accessible bycomputer 1012, and includes both volatile and non-volatile media, andremovable and non-removable media.

Memory 1028 can include computer system readable media in the form ofvolatile memory, such as random access memory (RAM) 1030 and/or cache1032. In one embodiment, cache 1032, and/or additional caches, areincluded in processing unit 1016. Computer 1012 may further includeother removable/non-removable, volatile/non-volatile computer systemstorage media. By way of example only, computer readable storage media1034 can be provided for reading from and writing to a non-removable,non-volatile magnetic media (not shown and typically called a “harddrive”). Although not shown, a magnetic disk drive for reading from andwriting to a removable, non-volatile magnetic disk (e.g., a “floppydisk”), and an optical disk drive for reading from or writing to aremovable, non-volatile optical disk such as a CD-ROM, DVD-ROM or otheroptical media can be provided. In such instances, each can be connectedto bus 1018 by one or more data media interfaces. As will be furtherdepicted and described below, memory 1028 may include at least oneprogram product having a set (e.g., at least one) of program modulesthat are configured to carry out some or all of the functions ofembodiments of the disclosure.

Program 1040, having one or more program modules 1042, may be stored inmemory 1028 by way of example, and not limitation, as well as anoperating system, one or more application programs, other programmodules, and program data. Each of the operating system, one or moreapplication programs, other program modules, and program data or somecombination thereof, may include an implementation of a networkingenvironment. In some embodiments, program modules 1042 generally carryout the functions and/or methodologies of embodiments of the disclosureas described herein, while in other embodiments, processing unit 1016generally carries out the functions and/or methodologies of embodimentsof the disclosure as described herein, while in yet other embodimentsother portions of computer 1012 generally carry out the functions and/ormethodologies of embodiments of the disclosure as described herein.

Computer 1012 may also communicate with one or more external devices1014 such as a keyboard, a pointing device, etc., as well as display1024; one or more devices that enable a user to interact with computer1012; and/or any devices (e.g., network card, modem, etc.) that enablecomputer 1012 to communicate with one or more other computing devices.Such communication can occur via Input/Output (I/O) interfaces 1022.Still yet, computer 1012 can communicate with one or more networks suchas a local area network (LAN), a general wide area network (WAN), and/ora public network (e.g., the Internet) via network adapter 1020. Asdepicted, network adapter 1020 communicates with the other components ofcomputer 1012 via bus 1018. It should be understood that although notshown, other hardware and/or software components could be used inconjunction with computer 1012. Examples, include, but are not limitedto: microcode, device drivers, redundant processing units, external diskdrive arrays, RAID systems, tape drives, and data archival storagesystems, etc.

Various embodiments may be implemented in a data processing systemsuitable for storing and/or executing program code that includes atleast one processor coupled directly or indirectly to memory elementsthrough a system bus. The memory elements include, for instance, localmemory employed during actual execution of the program code, bulkstorage, and cache memory which provide temporary storage of at leastsome program code in order to reduce the number of times code must beretrieved from bulk storage during execution.

Input/Output or I/O devices (including, but not limited to, keyboards,displays, pointing devices, DASD, tape, CDs, DVDs, thumb drives andother memory media, etc.) can be coupled to the system either directlyor through intervening I/O controllers. Network adapters may also becoupled to the system to enable the data processing system to becomecoupled to other data processing systems or remote printers or storagedevices through intervening private or public networks. Modems, cablemodems, and Ethernet cards are just a few of the available types ofnetwork adapters.

Referring to FIGS. 1-10, the present disclosure may be a system, amethod, and/or a computer program product. The computer program productmay include a computer readable storage medium (or media) havingcomputer readable program instructions thereon for causing a processorto carry out aspects of the present disclosure.

The computer readable storage medium can be a tangible device that canretain and store instructions for use by an instruction executiondevice. The computer readable storage medium may be, for example, but isnot limited to, an electronic storage device, a magnetic storage device,an optical storage device, an electromagnetic storage device, asemiconductor storage device, or any suitable combination of theforegoing. A non-exhaustive list of more specific examples of thecomputer readable storage medium includes the following: a portablecomputer diskette, a hard disk, a random access memory (RAM), aread-only memory (ROM), an erasable programmable read-only memory (EPROMor Flash memory), a static random access memory (SRAM), a portablecompact disc read-only memory (CD-ROM), a digital versatile disk (DVD),a memory stick, a floppy disk, a mechanically encoded device such aspunch-cards or raised structures in a groove having instructionsrecorded thereon, and any suitable combination of the foregoing. Acomputer readable storage medium, as used herein, is not to be construedas being transitory signals per se, such as radio waves or other freelypropagating electromagnetic waves, electromagnetic waves propagatingthrough a waveguide or other transmission media (e.g., light pulsespassing through a fiber-optic cable), or electrical signals transmittedthrough a wire.

Computer readable program instructions described herein can bedownloaded to respective computing/processing devices from a computerreadable storage medium or to an external computer or external storagedevice via a network, for example, the Internet, a local area network, awide area network and/or a wireless network. The network may comprisecopper transmission cables, optical transmission fibers, wirelesstransmission, routers, firewalls, switches, gateway computers and/oredge servers. A network adapter card or network interface in eachcomputing/processing device receives computer readable programinstructions from the network and forwards the computer readable programinstructions for storage in a computer readable storage medium withinthe respective computing/processing device.

Computer readable program instructions for carrying out operations ofthe present disclosure may be assembler instructions,instruction-set-architecture (ISA) instructions, machine instructions,machine dependent instructions, microcode, firmware instructions,state-setting data, or either source code or object code written in anycombination of one or more programming languages, including an objectoriented programming language such as Java, Smalltalk, C++ or the like,and conventional procedural programming languages, such as the “C”programming language or similar programming languages. The computerreadable program instructions may execute entirely on the user'scomputer, partly on the user's computer, as a stand-alone softwarepackage, partly on the user's computer and partly on a remote computeror entirely on the remote computer or server. In the latter scenario,the remote computer may be connected to the user's computer through anytype of network, including a local area network (LAN) or a wide areanetwork (WAN), or the connection may be made to an external computer(for example, through the Internet using an Internet Service Provider).In some embodiments, electronic circuitry including, for example,programmable logic circuitry, field-programmable gate arrays (FPGA), orprogrammable logic arrays (PLA) may execute the computer readableprogram instructions by utilizing state information of the computerreadable program instructions to personalize the electronic circuitry,in order to perform aspects of the present disclosure.

Aspects of the present disclosure are described herein with reference toflowchart illustrations and/or block diagrams of methods, apparatus(systems), and computer program products according to embodiments of thedisclosure. It will be understood that each block of the flowchartillustrations and/or block diagrams, and combinations of blocks in theflowchart illustrations and/or block diagrams, can be implemented bycomputer readable program instructions.

These computer readable program instructions may be provided to aprocessor of a general purpose computer, special purpose computer, orother programmable data processing apparatus to produce a machine, suchthat the instructions, which execute via the processor of the computeror other programmable data processing apparatus, create means forimplementing the functions/acts specified in the flowchart and/or blockdiagram block or blocks. These computer readable program instructionsmay also be stored in a computer readable storage medium that can directa computer, a programmable data processing apparatus, and/or otherdevices to function in a particular manner, such that the computerreadable storage medium having instructions stored therein comprises anarticle of manufacture including instructions which implement aspects ofthe function/act specified in the flowchart and/or block diagram blockor blocks.

The computer readable program instructions may also be loaded onto acomputer, other programmable data processing apparatus, or other deviceto cause a series of operational steps to be performed on the computer,other programmable apparatus or other device to produce a computerimplemented process, such that the instructions which execute on thecomputer, other programmable apparatus, or other device implement thefunctions/acts specified in the flowchart and/or block diagram block orblocks.

The flowchart and block diagrams in the Figures illustrate thearchitecture, functionality, and operation of possible implementationsof systems, methods, and computer program products according to variousembodiments of the present disclosure. In this regard, each block in theflowchart or block diagrams may represent a module, segment, or portionof instructions, which comprises one or more executable instructions forimplementing the specified logical function(s). In some alternativeimplementations, the functions noted in the block may occur out of theorder noted in the figures. For example, two blocks shown in successionmay, in fact, be executed substantially concurrently, or the blocks maysometimes be executed in the reverse order, depending upon thefunctionality involved. It will also be noted that each block of theblock diagrams and/or flowchart illustration, and combinations of blocksin the block diagrams and/or flowchart illustration, can be implementedby special purpose hardware-based systems that perform the specifiedfunctions or acts or carry out combinations of special purpose hardwareand computer instructions.

Although one or more examples have been provided herein, these are onlyexamples. Many variations are possible without departing from the spiritof the present disclosure. For instance, processing environments otherthan the examples provided herein may include and/or benefit from one ormore aspects of the present disclosure. Further, the environment neednot be based on the z/Architecture®, but instead can be based on otherarchitectures offered by, for instance, IBM®, Intel®, Sun Microsystems,as well as others. Yet further, the environment can include multipleprocessors, be partitioned, and/or be coupled to other systems, asexamples.

Although preferred embodiments have been depicted and described indetail herein, it will be apparent to those skilled in the relevant artthat various modifications, additions, substitutions and the like can bemade without departing from the spirit of the disclosure, and these are,therefore, considered to be within the scope of the disclosure, asdefined in the following claims.

What is claimed is:
 1. A computer system for salvaging a partiallyexecuted hardware transaction, the computer system comprising: a memory;and a processor in communication with the memory, wherein the computersystem is configured to perform a method, said method comprising:saving, by a processor, state information in a first code region of afirst hardware transaction; executing, by the processor, anabout-to-fail handler, the about-to-fail handler using the saved stateinformation to determine whether the first hardware transaction is to besalvaged or to be aborted; and based on the transaction being to besalvaged, using, by the processor executing the about-to-fail handler,the saved state information to determine what portion of the firsthardware transaction to salvage.
 2. The computer system of claim 1,further comprising salvaging a portion of the first hardware transactionby committing transaction stores to memory.
 3. The computer system ofclaim 1, wherein the first hardware transaction includes a mainoperation portion and at least one secondary action portion.
 4. Thecomputer system of claim 3, wherein using, by the processor executingthe about-to-fail handler, the saved state information to determinewhether the first hardware transaction is to be salvaged or to beaborted includes determining that the first hardware transaction is tobe aborted if the main operation portion of the first hardwaretransaction did not execute completely.
 5. The computer system of claim1, further comprising: starting, by the processor executing theabout-to-fail handler, execution of a second hardware transaction at apoint in a second code region of the about-to-fail handler indicated bythe saved state information; determining, by the processor executing theabout-to-fail handler, the execution of the second hardware transactioncompleted; and committing, by the processor executing the about-to-failhandler, speculative state of the completed execution of the secondhardware transaction.
 6. The computer system of claim 1, furthercomprising: prior to executing, by the processor, the about-to-failhandler, detecting, by the processor, an about to fail condition in thefirst code region of the first hardware transaction.
 7. The computersystem of claim 6, wherein the detecting, by the processor, the about tofail condition in the first code region of the first hardwaretransaction includes evaluating a next instruction to determine if itsexecution will cause a failure.
 8. A computer program product forsalvaging a partially executed hardware transaction, the computerprogram product comprising: a non-transitory computer readable storagemedium readable by a processing circuit and storing instructions forexecution by the processing circuit for performing a method comprising:saving, by a processor, state information in a first code region of afirst hardware transaction; executing, by the processor, anabout-to-fail handler, the about-to-fail handler using the saved stateinformation to determine whether the first hardware transaction is to besalvaged or to be aborted; and based on the transaction being to besalvaged, using, by the processor executing the about-to-fail handler,the saved state information to determine what portion of the firsthardware transaction to salvage.
 9. The computer program product ofclaim 8, further comprising salvaging a portion of the first hardwaretransaction by committing transaction stores to memory.
 10. The computerprogram product of claim 8, wherein the first hardware transactionincludes a main operation portion and at least one secondary actionportion.
 11. The computer program product of claim 10, wherein using, bythe processor executing the about-to-fail handler, the saved stateinformation to determine whether the first hardware transaction is to besalvaged or to be aborted includes determining that the first hardwaretransaction is to be aborted if the main operation portion of the firsthardware transaction did not execute completely.
 12. The computerprogram product of claim 8, further comprising: starting, by theprocessor executing the about-to-fail handler, execution of a secondhardware transaction at a point in a second code region of theabout-to-fail handler indicated by the saved state information;determining, by the processor executing the about-to-fail handler, theexecution of the second hardware transaction completed; and committing,by the processor executing the about-to-fail handler, speculative stateof the completed execution of the second hardware transaction.
 13. Thecomputer program product of claim 8, further comprising: determining, bythe processor executing the about-to-fail handler, the hardwaretransaction can be completed non-transactionally; and completing, by theprocessor executing the about-to-fail handler, the hardware transactionnon-transactionally.
 14. The computer program product of claim 8,further comprising: prior to executing, by the processor, theabout-to-fail handler, detecting, by the processor, an about to failcondition in the first code region of the first hardware transaction.15. The computer program product of claim 14, wherein the detecting, bythe processor, the about to fail condition in the first code region ofthe first hardware transaction includes evaluating a next instruction todetermine if its execution will cause a failure.
 16. The computerprogram product of claim 14, wherein the detecting, by the processor, anabout to fail condition in the first code region of the first hardwaretransaction includes determining that a limit on a number of nestedtransactions will be exceeded upon execution of an instruction withinthe code region.
 17. A method for salvaging a partially executedhardware transaction, the method comprising: saving, by a processor,state information in a first code region of a first hardwaretransaction; executing, by the processor, an about-to-fail handler, theabout-to-fail handler using the saved state information to determinewhether the first hardware transaction is to be salvaged or to beaborted; and based on the transaction being to be salvaged, using, bythe processor executing the about-to-fail handler, the saved stateinformation to determine what portion of the first hardware transactionto salvage.
 18. The method of claim 17, further comprising salvaging aportion of the first hardware transaction by committing transactionstores to memory.
 19. The method of claim 17, wherein the first hardwaretransaction includes a main operation portion and at least one secondaryaction portion.
 20. The method of claim 17, further comprising:starting, by the processor executing the about-to-fail handler,execution of a second hardware transaction at a point in a second coderegion of the about-to-fail handler indicated by the saved stateinformation; determining, by the processor executing the about-to-failhandler, the execution of the second hardware transaction completed; andcommitting, by the processor executing the about-to-fail handler,speculative state of the completed execution of the second hardwaretransaction.